(function (win) {

  function HebeFrame(option) {
    var WRAPPER_ORIGIN = win.location.origin;
    var HEBE_ORIGIN = option.hebeOrigin;
    var HEBE_PATH = option.hebePath;
    var container = document.querySelector('#' + option.containerId);

    if (!container) {
      console.log('[HebePlugin] #' + option.containerId + ' DOM not found.');
      return;
    } else if (container.children && container.children.length > 0) {
      console.log('[HebePlugin] #' + option.containerId + ' DOM already has children.');
      return;
    }

    function receiveMsg(event) {
      var msgObj = event.data;
      if (event.origin !== HEBE_ORIGIN) {
        return;
      }
      if (msgObj.name === 'hebe.init.ready') {
        sendConfig(event.source);
        // do not remove listener in case iframe refreshes
        // win.removeEventListener('message', receiveMsg, false);
      }
    }

    function sendConfig(targetWindow) {
      var config = {
        name: 'hebe.init.config',
        data: {
          accessToken: option.accessToken,
          apiHost: option.apiHost,
          other: option.other,
          wrapperOrigin: WRAPPER_ORIGIN,
          imAres: true,
          moduleOption: option.moduleOption,
        }
      };
      console.log('[HebePlugin] Sending config to Hebe ', config);
      targetWindow.postMessage(config, HEBE_ORIGIN);
      if ((typeof option.onReadyCallback).toUpperCase() === 'FUNCTION') {
        option.onReadyCallback();
      }
    }

    function createIframe() {
      var iframe = document.createElement('iframe');
      iframe.src = HEBE_ORIGIN + HEBE_PATH + '/?v=' + (new Date()).getTime() + '#/entry/' + option.route;
      iframe.style.border = 'none';
      iframe.style.width = '100%';
      iframe.style.height = '100%';
      container.appendChild(iframe);
    }

    win.addEventListener('message', receiveMsg, false);
    createIframe();
  }

  win.HebeFrame = HebeFrame;
})(window);
